'''
https://leetcode.cn/problems/design-in-memory-file-system
'''
from typing import List

class Node:
    def __init__(self, name=None, is_file = False, content=None):
        self.next = {}
        self.is_file = is_file
        self.name = name
        self.content = content

class FileSystem:

    def __init__(self):
        self.root = Node()

    # insert
    def mkdir(self, path: str) -> None:
        paths = [sub_path for sub_path in path.split('/') if sub_path]
        cur = self.root
        for sub_path in paths:
            if sub_path not in cur.next:
                cur.next[sub_path] = Node(name=sub_path)
            cur = cur.next[sub_path]

    def addContentToFile(self, filePath: str, content: str) -> None:
        paths = [sub_path for sub_path in filePath.split('/') if sub_path]
        cur = self.root
        for sub_path in paths[:-1]:
            cur = cur.next[sub_path]

        filename = paths[-1]
        if filename not in cur.next:
            cur.next[filename] = Node(name=filename, is_file=True, content=content)
        else:
            file = cur.next[filename]
            file.content += content

    # query
    def ls(self, path: str) -> List[str]:
        paths = [sub_path for sub_path in path.split('/') if sub_path]
        cur = self.root
        for sub_path in paths:
            cur = cur.next[sub_path]
        if cur.is_file:
            return [cur.name]
        res = []
        for sub_path in sorted(cur.next.keys()):
            res.append(sub_path)
        return res


    def readContentFromFile(self, filePath: str) -> str:
        paths = [sub_path for sub_path in filePath.split('/') if sub_path]
        cur = self.root
        for sub_path in paths:
            cur = cur.next[sub_path]
        return cur.content


